package com.easy.service.impl;

import cn.hutool.db.PageResult;
import com.easy.bean.PostBean;
import com.easy.bean.UserBean;
import com.easy.mapper.PostDao;
import com.easy.service.MessageService;
import com.easy.service.PostService;
import com.easy.util.LogMethod;
import com.easy.util.Page;
import com.easy.util.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
//@Transactional
public class PostServiceImpl implements PostService {

    @Autowired
    private PostDao postDao;

    @Autowired
    private MessageService messageService;

    @Override
    @Transactional
    @LogMethod(serviceName = "帖子创建",recordReturn = true)
    public PostBean add(PostBean post) {
        // 1. 参数校验
        if (post == null) {
            throw new IllegalArgumentException("帖子信息不能为空");
        }
        if (post.getUserId() == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        if (post.getPostTitle() == null || post.getPostTitle().trim().isEmpty()) {
            throw new IllegalArgumentException("帖子标题不能为空");
        }
        if (post.getPostContent() == null || post.getPostContent().trim().isEmpty()) {
            throw new IllegalArgumentException("帖子内容不能为空");
        }

        // 2. 设置默认值
        post.setStatus("draft"); // 默认草稿状态
        post.setIsVisible(1);   // 默认可见
        post.setGiveCount(0);   // 点赞数初始化为0
        post.setCommentCount(0); // 评论数初始化为0
        post.setCreatedAt(new Date());
        post.setUpdatedAt(new Date());

        // 3. 自动生成摘要（取内容前100字符）
        String content = post.getPostContent();
        if (content.length() > 100) {
            post.setPostSummary(content.substring(0, 100) + "...");
        } else {
            post.setPostSummary(content);
        }
        //保存数据库
        postDao.add(post);
        // 保存帖子（状态为draft）
        PostBean savedPost = postDao.getById(post.getId());
        // 如果发布（状态设为published），发送发布消息
        if ("published".equals(post.getStatus())) {
            messageService.sendPostPublishMessage(
                    savedPost.getUserId(),
                    savedPost.getId(),
                    savedPost.getPostTitle()
            );
        }

        // 5. 返回保存后的完整帖子信息
        return savedPost;
    }

    @Override
    @Transactional
    @LogMethod(serviceName = "帖子隐藏",recordReturn = true)
    public int del(Integer id) {
        // 1. 参数校验
        if (id == null) {
            throw new IllegalArgumentException("帖子ID不能为空");
        }

        // 2. 检查帖子是否存在
        PostBean existingPost = postDao.getById(id);
        if (existingPost == null) {
            throw new RuntimeException("帖子不存在或已被删除");
        }

        // 3. 执行软删除（设置isVisible=0）
        return postDao.del(id);
    }
    @Override
    @Transactional
    @LogMethod(serviceName = "帖子删除",recordReturn = true)
    public int delete(Integer id) {
        return postDao.delete(id);
    }

    @Override
    @Transactional
    @LogMethod(serviceName = "帖子更新",recordReturn = true)
    public PostBean update(PostBean post) {
        // 1. 参数校验
        if (post == null) {
            throw new IllegalArgumentException("帖子信息不能为空");
        }
        if (post.getId() == null) {
            throw new IllegalArgumentException("帖子ID不能为空");
        }

        // 2. 检查帖子是否存在
        PostBean existingPost = postDao.getById(post.getId());
        if (existingPost == null || existingPost.getIsVisible() == 0) {
            throw new RuntimeException("帖子不存在或已被删除");
        }

        // 3. 更新摘要（如果内容有变化）
        if (post.getPostContent() != null && !post.getPostContent().equals(existingPost.getPostContent())) {
            String content = post.getPostContent();
            if (content.length() > 100) {
                post.setPostSummary(content.substring(0, 100) + "...");
            } else {
                post.setPostSummary(content);
            }
        }

        // 4. 设置更新时间
        post.setUpdatedAt(new Date());

        // 5. 执行更新
        postDao.update(post);
        PostBean updatedPost = postDao.getById(post.getId());

        // 发送编辑消息
        messageService.sendPostEditMessage(
                updatedPost.getUserId(),
                updatedPost.getId(),
                updatedPost.getPostTitle()
        );
        // 6. 返回更新后的帖子信息
        return updatedPost;
    }

    @Override
    @LogMethod(serviceName = "帖子管理",recordReturn = true)
    public PostBean getId(Integer id) {
        // 1. 参数校验
        if (id == null) {
            throw new IllegalArgumentException("帖子ID不能为空");
        }

        // 2. 查询帖子
        PostBean post = postDao.getById(id);

        // 3. 检查帖子是否可见
        if (post == null || post.getIsVisible() == 0) {
            throw new RuntimeException("帖子不存在或已被删除");
        }

        return post;
    }
    @Override
    public List<PostBean> getPostsByUserId(Integer userId) {
        return postDao.selectByUserId(userId);
    }

    @Override
    @LogMethod(serviceName = "帖子类型查询",recordReturn = true)
    public List<PostBean> listByType(Integer typeId) {
        // 1. 参数校验
        if (typeId == null) {
            throw new IllegalArgumentException("分类ID不能为空");
        }

        // 2. 查询指定分类下的帖子
        return postDao.listByType(typeId);
    }


    @Override
    public void searchByTitle(String keyword, Page page) {
        // 1. 获取总数
        int count = postDao.countSearchByTitle(keyword);
        page.setCount(count);

        // 2. 查询当前页数据
        List<PostBean> data = postDao.searchByTitle(keyword, page);

        // 3. 设置分页结果
        page.setData(data);
    }

    @Override
    public List<PostBean> list(PostBean post) {
        return postDao.list(post);
    }

    @Override
    public PostBean get(Integer id) {
        // 复用getId方法
        return getId(id);
    }


    @Override
    public void page(Page page, PostBean post) {
        // 2. 计算总数
        int count = postDao.pageCount(post);
        page.setCount(count);

        // 3. 查询当前页数据
        List<PostBean> data = postDao.page(page, post);

        // 4. 设置分页结果
        page.setData(data);
    }
    @Override
    public void listPage(Page page, PostBean post) {
        int count = postDao.listPageCount(post);
        List<PostBean> data = postDao.listPage(page, post);
        page.setCount(count);
        page.setData(data);
    }

}